﻿using log4net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace WebApp.App_Code
{
    public class GlobalExceptionFilter: IExceptionFilter
    {
        readonly IWebHostEnvironment hostEnvironment;
        readonly ILog logger;
        public GlobalExceptionFilter(IWebHostEnvironment _hostEnvironment)
        {
            this.hostEnvironment = _hostEnvironment;
            this.logger = LogManager.GetLogger(typeof(GlobalExceptionFilter));
        }
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)//如果异常没有处理
            {
                var result = new ApiResult
                {
                    Code = 500,
                    IsSuccess = false,
                    Message = "服务器发生未处理的异常"
                };

                if (hostEnvironment.IsDevelopment())
                {
                    result.Message += "，" + context.Exception.Message;
                    result.Data = context.Exception.StackTrace;
                }

                logger.Error(result.Message, context.Exception);

                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;//异常已处理
            }
        }
    }
}
